#include "WidgetFade.h"

WidgetFade::WidgetFade(QList<QWidget *> widgetList, QObject *parent) :QThread(parent){
    this -> effectList = new QList<QGraphicsOpacityEffect*>();
    this -> widgetList = new QList<QWidget*>();
    this -> actuallyFading = false;
    setWidgetList(widgetList);
}

WidgetFade::WidgetFade(QWidget * widget, QObject *parent) :QThread(parent){
    this -> widgetList = new QList<QWidget*>();
    this -> effectList = new QList<QGraphicsOpacityEffect*>();
    this -> actuallyFading = false;

    this -> widgetList -> append(widget);
    setEffectList();
}


WidgetFade::~WidgetFade(){
    delete this->widgetList;
    delete this->effectList;
}

void WidgetFade::setSpeed(float speed){
    this -> speed = speed;

}


void WidgetFade::clearWidgetList(){
    this->widgetList -> clear();
    this->effectList -> clear();
}


void WidgetFade::setWidgetList(QList<QWidget*> widgetList){
    clearWidgetList();
    for (int i = 0; i < widgetList.size(); i++){
        this->widgetList -> append(widgetList.at(i));
    }
    setEffectList();
}


void WidgetFade::setEffectList(){
    for (int i = 0; i < this->widgetList -> size(); i++){
        this -> effectList -> append(new QGraphicsOpacityEffect(this->widgetList -> at(i)));
        connect(this, SIGNAL(signalChangeOpacity(qreal)), this->effectList -> at(i), SLOT(setOpacity(qreal)));
    }
}


void WidgetFade::fade(float currentOpacity, float newOpacity, float speed){
    setSpeed(speed);
    this -> newOpacity = newOpacity;
    if (!isFading()){
        this -> currentOpacity = currentOpacity;
        this -> start();
    } else {
        stopFading();
        this -> start();
    }
}


void WidgetFade::stopFading(){
    this -> actuallyFading = false;
    this -> wait();
}


bool WidgetFade::isFading(){
    return this->actuallyFading;
}


int WidgetFade::getTime(){
    return 3 * this -> speed * 50;
}



void WidgetFade::run(){
    this -> actuallyFading = true;
    while (qAbs(this->newOpacity - this->currentOpacity) > 0.01 && this -> actuallyFading){
        this -> currentOpacity += (this -> newOpacity - currentOpacity) / this->speed;
        for (int j = 0; j < this->widgetList -> size(); j++){
            this -> effectList -> at(j) -> setOpacity(this -> currentOpacity);
            this -> widgetList -> at(j) -> setGraphicsEffect(this -> effectList -> at(j));
            this -> widgetList -> at(j) -> update();
        }
        this->msleep(50);
    }
    this -> actuallyFading = false;
}


